package com.yksj.healthtalk.ui.dictionary;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.dictionary.DictionaryContentListFragment.DictionnaryContentListItemClickListener;
import com.yksj.healthtalk.ui.server.ServerShopSeachActivity;
import com.yksj.healthtalk.utils.ViewUtils;


/**
 * 
 * 用于需要赛选的listview
 * @author zhao
 * 
 */
public class DictionaryListFragment extends Fragment implements OnClickListener{
	DictionnaryContentListItemClickListener clickListener;
	ListView mListView;
	DictionaryListAdapter adapter;
	
	String mType;
	int mIndex;
	Map<String,JSONArray> mTypeMap;
	
	public static DictionaryListFragment instantiate(Context context,Bundle bundle){
		return (DictionaryListFragment)Fragment.instantiate(context,DictionaryListFragment.class.getName(),bundle);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mIndex = getArguments().getInt("index");
		mType = getArguments().getString("type");
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if(getActivity() instanceof DictionnaryContentListItemClickListener){
			clickListener = (DictionnaryContentListItemClickListener)getActivity();
		}
		String content = getArguments().getString("parame");
		try{
			adapter = new DictionaryListAdapter(getActivity());
			mListView.setAdapter(adapter);
			JSONTokener jsonTokener = new JSONTokener(content);
			Object object = jsonTokener.nextValue();
			if(object instanceof JSONArray){
				onDataTypeSort((JSONArray)object);
			}else if(object instanceof JSONObject){
				JSONArray jsonArray = ((JSONObject)object).getJSONArray("data");
				onDataTypeSort(jsonArray);
			}
		}catch(JSONException e){
			e.printStackTrace();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case 10:
		case 20:
		case 30:	
			v.showContextMenu();
			break;
		}
	}
	
	/**
	 * 对数据进行分类
	 * @param jsonArray
	 */
	private void onDataTypeSort(JSONArray jsonArray){
		mTypeMap = new LinkedHashMap<String, JSONArray>();
		mTypeMap.put(getString(R.string.limit_no),jsonArray);
		for (int i = 0; i < jsonArray.length(); i++) {
			try {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				String type = null;
				
				if(jsonObject.has("LEVEL_NAME")){
					type = jsonObject.getString("LEVEL_NAME");
				}else if(jsonObject.has("TYPE")){
					type = jsonObject.getString("TYPE");
				}
				boolean isContain = mTypeMap.containsKey(type);
				JSONArray array;
				if(isContain){
					array = mTypeMap.get(type);
				}else{
					array = new JSONArray();
					mTypeMap.put(type, array);
				}
				array.put(jsonObject);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		adapter.onDataChange(jsonArray);
	}
	
	/**
	 * 上下文赛选菜单
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if(mTypeMap == null)return;
		if("10015".equals(mType)){//附近就医,等级赛选
			menu.setHeaderTitle("选择等级");
			for (String key : mTypeMap.keySet()) {
				menu.add(key);
			} 
		}else if("10016".equals(mType)){//附近药店,类型赛选
			for (String key : mTypeMap.keySet()) {
				menu.add(key);
			} 
		}else if("5".equals(mType) && mIndex == 2){//医院等级赛选
			for (String key : mTypeMap.keySet()) {
				menu.add(key);
			} 
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		JSONArray jsonArray = mTypeMap.get(item.toString());
		adapter.onDataChange(jsonArray);
		return super.onContextItemSelected(item);
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.dictionary_content_list_layout,null);
		mListView = (ListView)view.findViewById(android.R.id.list);
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				--position;
				JSONObject jsonObject = adapter.getItem(position);
				String code = adapter.getCode(jsonObject);
				String name = adapter.getName(jsonObject);
				adapter.onSelect(jsonObject);
				adapter.notifyDataSetChanged();
				if(clickListener != null)clickListener.onContentItemClick(name, code,mIndex);
			}
		});
		mListView.setEmptyView(view.findViewById(R.id.list_empty));
		if("10015".equals(mType)){
			View view2 = inflater.inflate(R.layout.dictionary_filter_btn,null);
			Button button = (Button)(view2.findViewById(R.id.dictionary_filter1));
			button.setText("医院类型");
			button.setId(10);
			button.setOnClickListener(this);
			mListView.addHeaderView(view2, null,false);
			registerForContextMenu(button);
		}else if("10016".equals(mType)){
			View view2 = inflater.inflate(R.layout.dictionary_filter_btn,null);
			Button button = (Button)(view2.findViewById(R.id.dictionary_filter1));
			button.setText("药店类型");
			button.setId(20);
			button.setOnClickListener(this);
			mListView.addHeaderView(view2, null,false);
			registerForContextMenu(button);
		}else if("5".equals(mType) && mIndex == 2){//医院等级
			View view2 = inflater.inflate(R.layout.dictionary_filter_btn,null);
			Button button = (Button)(view2.findViewById(R.id.dictionary_filter1));
			button.setText("选择等级");
			button.setId(30);
			button.setOnClickListener(this);
			mListView.addHeaderView(view2, null,false);
			registerForContextMenu(button);
		}else if("10004".equals(mType)){
			View view2 = inflater.inflate(R.layout.dictionary_filter_btn,null);
			Button button = (Button)(view2.findViewById(R.id.dictionary_filter1));
			button.setText("去药品中心");
			button.setId(30);
			button.setOnClickListener(this);
			mListView.addHeaderView(view2, null,false);
			button.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(),ServerShopSeachActivity.class);
					intent.putExtra("code",getArguments().getString("code"));
					startActivity(intent);
				}
			});
//			registerForContextMenu(button);
		
		//跳转到药品中心	
		}else if("10005".equals(mType) || "10006".equals(mType)){
			View view2 = inflater.inflate(R.layout.dictionary_filter_btn,null);
			Button button = (Button)(view2.findViewById(R.id.dictionary_filter1));
			button.setText("去药品中心");
			button.setId(30);
			button.setOnClickListener(this);
			mListView.addHeaderView(view2, null,false);
			button.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(),ServerShopSeachActivity.class);
					intent.putExtra("code",getArguments().getString("code"));
					startActivity(intent);
				}
			});
//			registerForContextMenu(button);
		}
		return view;
	}
	
	
	private class DictionaryListAdapter extends BaseAdapter{
		JSONArray array = new JSONArray();
		final LayoutInflater mInflater;
		final List<Object> mSelectedList = new ArrayList<Object>();
		final DecimalFormat mDecimalFormat = new DecimalFormat("00.00");
		
		public DictionaryListAdapter(Context context,JSONArray array){
			this(context);
			this.array = array;
		}
		
		public DictionaryListAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}
		
		public void onSelect(Object object){
			mSelectedList.clear();
			mSelectedList.add(object);
		}
		
		public boolean isSeleted(Object obj){
			return mSelectedList.contains(obj);
		}
		
		private void onDataChange(JSONArray jsonArray){
			this.array = jsonArray;
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return array.length();
		}

		@Override
		public JSONObject getItem(int position) {
			JSONObject jsonObject = null;
			try {
				jsonObject = array.getJSONObject(position);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return jsonObject;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if(convertView == null){
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.dictionary_textview, null);
				holder.nameTextV = (TextView)convertView.findViewById(R.id.textview1);
				holder.levelTextV = (TextView)convertView.findViewById(R.id.level);
				holder.distanceTetV = (TextView)convertView.findViewById(R.id.distance);
				holder.textView3 = (TextView)convertView.findViewById(R.id.text3);
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder)convertView.getTag();
			}
			
			JSONObject jsonObject = getItem(position);
//			String distance = getDistance(jsonObject);
			//if(distance != null)holder.distanceTetV.setText(distance+"公里");
			String name  = getName(jsonObject);
			boolean  isSelected = isSeleted(jsonObject);
			if(isSelected){
				convertView.setBackgroundColor(getResources().getColor(R.color.orange));
				convertView.setSelected(true);
			}else{
				convertView.setBackgroundResource(R.color.dictionary_selector2);
				convertView.setSelected(false);
			}
			
			if(jsonObject.has("LEVEL_NAME")){
				holder.levelTextV.setText(getLevel(jsonObject));
			}
			ViewUtils.setGone(holder.levelTextV,!jsonObject.has("LEVEL_NAME"));
			
			
			if(getStandards(jsonObject) != null){
				holder.levelTextV.setText(getStandards(jsonObject));
			}
			ViewUtils.setGone(holder.levelTextV, getStandards(jsonObject)  == null);
			
			if(getFactory(jsonObject) != null){
				holder.distanceTetV.setText(getFactory(jsonObject));
			}
			ViewUtils.setGone(holder.distanceTetV,getFactory(jsonObject) == null);
			
			if(getLotNumber(jsonObject) != null){
				holder.textView3.setText(getLotNumber(jsonObject));
			}
			ViewUtils.setGone(holder.textView3, getLotNumber(jsonObject) == null);
			holder.nameTextV.setText(name);
			return convertView;
		}
		
		/**
		 * 获得距离
		 * @param jsonObject
		 * @return
		 */
		private String getDistance(JSONObject jsonObject){
			double distance = jsonObject.optDouble("DISTANCE",0.0d);
			return mDecimalFormat.format(distance);
		}
		
		private String getName(JSONObject jsonObject){
			if(jsonObject == null)return "";
			try {
				String name = jsonObject.getString("NAME");
				return name;
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return "";
		}
		
		private String getCode(JSONObject jsonObject){
			if(jsonObject == null)return "";
			try {
				String code = jsonObject.getString("CODE");
				return code;
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return "";
		}
		
		private String getStandards(JSONObject object){
			return object.optString("STANDARDS", null);
		}
		
		private String getFactory(JSONObject object){
			return object.optString("FACTORY", null);
		}
		
		private String getLotNumber(JSONObject object){
			return object.optString("LOT_NUMBER", null);
		}
		
		/**
		 * 获得级别
		 * @param jsonObject
		 * @return
		 */
		private String getLevel(JSONObject jsonObject){
			if(jsonObject == null)return "";
			try {
				String code = jsonObject.getString("LEVEL_NAME");
				return code;
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return "";
		}
	}
	
	static class ViewHolder{
		TextView nameTextV;
		TextView levelTextV;
		TextView distanceTetV;
		TextView textView3;
	}
}
